# -*- coding: utf-8 -*-
import hashlib
import json
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://svc.zqian28.com/api/CreatePayOrder'

APP_CONF = {
    '1021': {
        'API_KEY': 'bdKfZqiWJrTqrRlm1LTmepzrG8nViHGE',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'Key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_notify_sign(d, key, PayMoney, SettleMoney):
    s = 'PayMoney={}&SettleMoney={}&OrderNo={}&AgentOrder={}&Key={}'.format(
        PayMoney, SettleMoney, d['OrderNo'], d['AgentOrder'], key
    )
    _LOGGER.info('yftpay generate_notify_sign s :%s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key, PayMoney, SettleMoney):
    sign = params['Sign']
    calculated_sign = generate_notify_sign(params, key, PayMoney, SettleMoney)
    if sign != calculated_sign:
        _LOGGER.info("yftpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 3.QQH5；4.快捷；5.微信扫码；6.支付宝扫码,8.支付宝H5
def _get_pay_type(paytype):
    if paytype == 'qq':
        return '3'
    elif paytype == 'alipay':
        return '8'
    elif paytype == 'union':
        return '4'
    else:
        return '4'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('AgentID', app_id),
        ('OrderNo', str(pay.id)),
        ('ClientIp', _get_device_ip(info)),
        ('GoodsName', 'charge'),
        ('PayMoney', str(int(pay_amount * 100))),
        ('PayModel', _get_pay_type(service)),
        ('NotifyUrl', '{}/pay/api/{}/yftpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ReturnUrl', '{}/pay/api/{}/yftpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("yftpay create charge data: %s %s",
                 response.status_code, response.text)
    res_obj = json.loads(response.text)
    if service == 'alipay':
        return {'charge_info': res_obj['data']}
    cache_id = redis_cache.save_html(pay.id, res_obj['data'])
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("yftpay notify s: %s", request.body)
    t = urllib.unquote(request.body)
    PayMoney = _get_str(t, '"PayMoney":', ',')
    SettleMoney = _get_str(t, '"SettleMoney":', ',')
    data = json.loads(t)['data'][0]
    verify_notify_sign(data, api_key, PayMoney, SettleMoney)
    pay_id = data['AgentOrder']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yftpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = _get_str(t, '"status":', ',')
    trade_no = data['OrderNo']
    total_fee = float(data['PayMoney']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '10000':
        _LOGGER.info('yftpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
